﻿using Aliyun.Acs.Alidns.Model.V20150109;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using com.ruovea.ddns.util;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;

namespace com.ruovea.aliyun.ddns.api
{
    public class AliyunDomainRecord : IDomainRecord
    {

        IConfiguration _configuration;
        string _accessKey = string.Empty;
        string _accessSecret = string.Empty;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        public AliyunDomainRecord(IConfiguration configuration)
        {
            this._configuration = configuration;
            _accessKey = _configuration.GetSection("aliyun:accessKey")?.Value;
            _accessSecret = _configuration.GetSection("aliyun:accessSecret")?.Value;
        }

        /// <summary>
        /// 获取 记录
        /// </summary>
        /// <param name="domainName"></param>
        /// <returns></returns>
        public IEnumerable<DescribeRecord> GetRecords(string domainName)
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", _accessKey, _accessSecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);

            var request = new DescribeDomainRecordsRequest();
            request.DomainName = domainName;
            request.TypeKeyWord = "A";

            var response = client.GetAcsResponse(request);
            if (response.TotalCount == 0)
            {
                throw new Exception("请先手动解析几条A记录");
            }

            return response.DomainRecords.Select(x => new DescribeRecord()
            {
                RecordId = x.RecordId,
                Value = x.Value,
                RR = x.RR,
                Type = x.Type,
            });
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="record"></param>
        public void UpdateRecord(DescribeRecord record)
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", _accessKey, _accessSecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);

            var request = new UpdateDomainRecordRequest();
            request.RecordId = record.RecordId;
            request.RR = record.RR;
            request.Type = record.Type;
            request.Value = record.Value;

            try
            {
                var response = client.GetAcsResponse(request);
            }
            catch (ServerException e)
            {
                Console.WriteLine(e);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
            }
        }
        /// <summary>
        /// 执行刷新程序
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="ignoreRR"></param>
        public void Refresh()
        {
            string domain = _configuration.GetSection("aliyun:domain")?.Value?.Trim();
            string ignoreRR = _configuration.GetSection("aliyun:ignoreRR")?.Value?.Trim();

            var current_ip = IpHelper.CurrentIp();
            var records = this.GetRecords(domain);

            if (!string.IsNullOrEmpty(ignoreRR))
            {
                var igs = ignoreRR.Split("|");
                records = records.Where(x => x.Type == "A" && !igs.Contains(x.RR));
            }

            if (!records.Any(x => x.Value != current_ip))
            {
                Console.WriteLine($"{DateTime.Now} ip没有改变 {current_ip}");
                return;
            }

            Console.WriteLine($"{DateTime.Now} 更新A解析记录 {current_ip}");

            // 更新记录
            foreach (var item in records)
            {
                item.Value = current_ip;
                this.UpdateRecord(item);
            }
        }
    }
}
